package com.powernode.shop.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.shop.anno.Log;
import com.powernode.shop.domain.SysUser;
import com.powernode.shop.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/10
 */

@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/info")
    public ResponseEntity<SysUser> info(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        System.out.println("********************authentication = " + authentication);
        String userId = authentication.getPrincipal().toString();
        SysUser sysUser = sysUserService.getById(userId);
        return ResponseEntity.ok(sysUser);
    }

    /**
     * 分页查询，条件：1、当前页，2.每页显示记录数，3.用户名查询
     * @param page
     * @param sysUser
     * @return
     */
    @PreAuthorize("hasAuthority('sys:user:page')")
    @GetMapping("/page")
    public ResponseEntity<Page<SysUser>> pageSysUser(Page<SysUser> page,SysUser sysUser){
        return ResponseEntity.ok(sysUserService.getPage(page, sysUser));
    }

    /**
     * 添加用户
     * @param sysUser
     * @return
     */
    @Log(operation = "添加用户")        // 测试面向切面 添加日志
    @PreAuthorize("hasAuthority('sys:user:save')")
    @PostMapping
    public ResponseEntity<Void> saveUser(@RequestBody SysUser sysUser){
        // security上下文先得到权限对象 得到暴露的替换userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getPrincipal().toString();
        // 放入创建者对象
        sysUser.setCreateUserId(Long.valueOf(userId));
        sysUserService.save(sysUser);
        return ResponseEntity.ok().build();
    }

}
